package com.dfbz.filter;

import com.dfbz.service.UserService;
import com.dfbz.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebFilter("/index.jsp")
public class SignFilter implements Filter {
    private UserService userService=new UserServiceImpl();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie:cookies){
            if ("uName".equals(cookie.getName())){
                HttpSession session = req.getSession();
                String sId = session.getId();
                //将用户的真实名字以及部门名称查出来（查询用户基本信息）
                Map<String,Object> map=userService.findUserBaseInfo(cookie.getValue());
                session.setAttribute("userBaseInfo",map);
                session.setAttribute(sId,map.get("user_id").toString());
                resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
                return;
            }
        }
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
